<template>
  <div class="personal-center">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <i class="iconfont icon-book"></i>
        <span>考研真题训练系统</span>
      </div>
      <div class="user-info">
        <span class="welcome">欢迎回来，{{ userStore.username }}</span>
        <el-avatar :size="40" :src="userInfo.avatar"></el-avatar>
      </div>
    </header>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 侧边导航 -->
      <div class="sidebar">
        <div class="user-card">
          <el-avatar :size="80" :src="userInfo.avatar"></el-avatar>
          <div class="user-details">
            <h3>{{ userStore.username }}</h3>
            <p>VIP {{ userInfo.vipLevel }} 会员</p>
            <p>积分: {{ userInfo.points }}</p>
          </div>
        </div>

        <el-menu
          default-active="4"
          class="side-menu"
        >
          <el-menu-item index="1">
            <router-link to="/personal-center/info" class="menu-link">
              <i class="iconfont icon-user"></i>
              <span>个人信息</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="2">
            <router-link to="/personal-center/edit" class="menu-link">
              <i class="iconfont icon-edit"></i>
              <span>修改资料</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="3">
            <router-link to="/personal-center/feedback" class="menu-link">
              <i class="iconfont icon-message"></i>
              <span>消息反馈</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="4" class="active">
            <router-link to="/personal-center/notifications" class="menu-link">
              <i class="iconfont icon-notification"></i>
              <span>通知设置</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="5">
            <router-link to="/personal-center/cancel-account" class="menu-link">
              <i class="iconfont icon-logout"></i>
              <span>注销账户</span>
            </router-link>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区 -->
      <div class="content">
        <!-- 当前时间显示 -->
        <div class="current-time">
          <span>当前时间：{{ currentTime }}</span>
        </div>
        

        
        <!-- 通知设置 -->
        <div class="notification-section">
          <h2 class="section-title">通知设置</h2>
          <div class="notification-card">
            <!-- 每日任务提醒 -->
            <div class="notification-item">
              <div class="notification-info">
                <h3>每日任务提醒</h3>
                <p>提醒您完成每日学习任务</p>
                <p v-if="notificationSettings.dailyTask.enabled" class="next-reminder">
                  设置时间: {{ notificationSettings.dailyTask.time }}
                </p>
                <p v-if="notificationSettings.dailyTask.enabled && notificationSettings.dailyTask.lastTriggered" class="last-reminder">
                  上次提醒: {{ formatTime(notificationSettings.dailyTask.lastTriggered) }}
                </p>
              </div>
              <div class="notification-settings">
                <el-switch v-model="notificationSettings.dailyTask.enabled" active-color="#409EFF" @change="toggleDailyReminder"></el-switch>
                <el-time-picker
                  v-model="notificationSettings.dailyTask.time"
                  :disabled="!notificationSettings.dailyTask.enabled"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="选择时间"
                  :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
                  @change="updateReminderTime('dailyTask')"
                >
                </el-time-picker>
              </div>
            </div>
            
            <!-- 帖子回复提醒 -->
            <div class="notification-item">
              <div class="notification-info">
                <h3>帖子回复提醒</h3>
                <p>当有人回复您的帖子时提醒</p>
                <p v-if="notificationSettings.postReply.enabled" class="next-reminder">
                  设置时间: {{ notificationSettings.postReply.time }}
                </p>
                <p v-if="notificationSettings.postReply.enabled && notificationSettings.postReply.lastTriggered" class="last-reminder">
                  上次提醒: {{ formatTime(notificationSettings.postReply.lastTriggered) }}
                </p>
              </div>
              <div class="notification-settings">
                <el-switch v-model="notificationSettings.postReply.enabled" active-color="#409EFF" @change="togglePostReminder"></el-switch>
                <el-time-picker
                  v-model="notificationSettings.postReply.time"
                  :disabled="!notificationSettings.postReply.enabled"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="选择时间"
                  :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
                  @change="updateReminderTime('postReply')"
                >
                </el-time-picker>
              </div>
            </div>
            
            <div class="save-settings">
              <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 提醒弹窗 -->
    <el-dialog
      :title="reminder.title"
      :visible.sync="showReminder"
      width="400px"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <div class="reminder-content">
        <div class="reminder-icon">
          <i class="iconfont icon-bell" style="color: #409EFF; font-size: 48px;"></i>
        </div>
        <div class="reminder-message">{{ reminder.message }}</div>
        <div class="reminder-time">{{ reminder.time }}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="snoozeReminder(5)">稍后提醒(5分钟)</el-button>
        <el-button type="primary" @click="dismissReminder">我知道了</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { useUserStore } from '@/store/user'
import { ref, onMounted } from 'vue'

export default {
  name: 'NotificationSettings',
  setup() {
    const userStore = useUserStore()
    
    onMounted(() => {
      userStore.initialize()
    })
    
    return {
      userStore
    }
  },
  data() {
    return {
      userInfo: {
        username: '考研学子',
        email: 'kaoyan@example.com',
        phone: '13800138000',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        vipLevel: 3,
        points: 1280,
        vipExpiry: '2024-12-31',
        studyDays: 86,
        completed: 1240,
        correctRate: 78
      },
      notificationSettings: {
        dailyTask: {
          enabled: true,
          time: '09:00',
          lastTriggered: null,
          triggered: false // 今日是否已触发
        },
        postReply: {
          enabled: true,
          time: '18:30',
          lastTriggered: null,
          triggered: false // 今日是否已触发
        }
      },
      showReminder: false,
      reminder: {
        title: '',
        message: '',
        time: '',
        type: ''
      },
      currentTime: '',
      timeChecker: null, // 时间检查器
      clockTimer: null // 时钟定时器
    };
  },
  created() {
    this.updateCurrentTime();
    this.startTimeChecker();
    this.loadSettings();
  },
  beforeDestroy() {
    this.stopTimeChecker();
  },
  methods: {
    // 更新当前时间显示
    updateCurrentTime() {
      const now = new Date();
      this.currentTime = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    // 启动时间检查器
    startTimeChecker() {
      // 每秒更新时间显示和检查提醒
      this.clockTimer = setInterval(() => {
        this.updateCurrentTime();
        this.checkReminders();
      }, 1000);

      // 立即检查一次
      this.checkReminders();
    },

    // 停止时间检查器
    stopTimeChecker() {
      if (this.timeChecker) {
        clearInterval(this.timeChecker);
        this.timeChecker = null;
      }
      if (this.clockTimer) {
        clearInterval(this.clockTimer);
        this.clockTimer = null;
      }
    },

    // 检查提醒时间
    checkReminders() {
      const now = new Date();
      const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
      const currentDate = now.toDateString();
      const currentSeconds = now.getSeconds();

      // 只在每分钟的第0秒检查，避免重复触发
      if (currentSeconds !== 0) {
        return;
      }

      // 检查每日任务提醒
      if (this.notificationSettings.dailyTask.enabled && 
          this.notificationSettings.dailyTask.time === currentTime) {
        
        const lastTriggeredDate = this.notificationSettings.dailyTask.lastTriggered ? 
          new Date(this.notificationSettings.dailyTask.lastTriggered).toDateString() : null;
        
        // 如果今天还没有触发过提醒
        if (lastTriggeredDate !== currentDate) {
          this.showDailyTaskReminder();
          this.notificationSettings.dailyTask.lastTriggered = now.getTime();
          this.saveSettings();
        }
      }

      // 检查帖子回复提醒
      if (this.notificationSettings.postReply.enabled && 
          this.notificationSettings.postReply.time === currentTime) {
        
        const lastTriggeredDate = this.notificationSettings.postReply.lastTriggered ? 
          new Date(this.notificationSettings.postReply.lastTriggered).toDateString() : null;
        
        // 如果今天还没有触发过提醒
        if (lastTriggeredDate !== currentDate) {
          this.showPostReplyReminder();
          this.notificationSettings.postReply.lastTriggered = now.getTime();
          this.saveSettings();
        }
      }
    },

    // 显示每日任务提醒
    showDailyTaskReminder() {
      this.reminder = {
        title: '每日任务提醒',
        message: '您有每日学习任务待完成，请及时查看并完成今日任务！',
        time: `提醒时间：${new Date().toLocaleString('zh-CN')}`,
        type: 'dailyTask'
      };
      this.showReminder = true;
      
      // 播放提醒音效（如果浏览器支持）
      this.playNotificationSound();
      
      // 显示系统通知（如果用户允许）
      this.showBrowserNotification('每日任务提醒', '您有每日学习任务待完成！');
    },

    // 显示帖子回复提醒
    showPostReplyReminder() {
      this.reminder = {
        title: '帖子回复提醒',
        message: '您的帖子有了新的回复，快去看看吧！',
        time: `提醒时间：${new Date().toLocaleString('zh-CN')}`,
        type: 'postReply'
      };
      this.showReminder = true;
      
      // 播放提醒音效
      this.playNotificationSound();
      
      // 显示系统通知
      this.showBrowserNotification('帖子回复提醒', '您的帖子有了新的回复！');
    },

    // 播放提醒音效
    playNotificationSound() {
      try {
        // 创建音频上下文（如果浏览器支持）
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();

        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);

        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);

        oscillator.start();
        oscillator.stop(audioContext.currentTime + 0.3);
      } catch (error) {
        console.log('无法播放提醒音效:', error);
      }
    },

    // 显示浏览器系统通知
    showBrowserNotification(title, message) {
      if ('Notification' in window) {
        if (Notification.permission === 'granted') {
          new Notification(title, {
            body: message,
            icon: '/favicon.ico'
          });
        } else if (Notification.permission !== 'denied') {
          Notification.requestPermission().then(permission => {
            if (permission === 'granted') {
              new Notification(title, {
                body: message,
                icon: '/favicon.ico'
              });
            }
          });
        }
      }
    },

    // 处理弹窗关闭
    handleClose(done) {
      this.$confirm('确认关闭提醒？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },

    // 关闭提醒
    dismissReminder() {
      this.showReminder = false;
      this.$message.success('提醒已关闭');
    },

    // 稍后提醒
    snoozeReminder(minutes) {
      this.showReminder = false;
      
      setTimeout(() => {
        if (this.reminder.type === 'dailyTask') {
          this.showDailyTaskReminder();
        } else {
          this.showPostReplyReminder();
        }
      }, minutes * 60 * 1000);
      
      this.$message.success(`将在${minutes}分钟后再次提醒您`);
    },



    // 切换每日提醒
    toggleDailyReminder(enabled) {
      if (!enabled) {
        this.notificationSettings.dailyTask.lastTriggered = null;
      }
      this.saveSettings();
      this.$message.success(enabled ? '每日任务提醒已开启' : '每日任务提醒已关闭');
    },

    // 切换帖子提醒
    togglePostReminder(enabled) {
      if (!enabled) {
        this.notificationSettings.postReply.lastTriggered = null;
      }
      this.saveSettings();
      this.$message.success(enabled ? '帖子回复提醒已开启' : '帖子回复提醒已关闭');
    },

    // 更新提醒时间
    updateReminderTime(type) {
      // 重置当日触发状态，允许在新时间再次触发
      this.notificationSettings[type].lastTriggered = null;
      this.saveSettings();
      this.$message.success('提醒时间已更新');
    },

    // 保存通知设置
    saveNotificationSettings() {
      this.$message.success('通知设置已保存');
      this.saveSettings();
    },

    // 保存设置到localStorage
    saveSettings() {
      try {
        localStorage.setItem('notificationSettings', JSON.stringify(this.notificationSettings));
      } catch (error) {
        console.error('保存设置失败:', error);
      }
    },

    // 加载设置
    loadSettings() {
      try {
        const saved = localStorage.getItem('notificationSettings');
        if (saved) {
          const settings = JSON.parse(saved);
          this.notificationSettings = { ...this.notificationSettings, ...settings };
        }
      } catch (error) {
        console.error('加载设置失败:', error);
      }
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '从未';
      return new Date(timestamp).toLocaleString('zh-CN');
    },

    // 页面跳转
    goToPage(pageName) {
      window.location.href = `./${pageName}`;
    }
  }
};
</script>

<style scoped>
.current-time {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 10px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
  font-weight: 500;
  font-size: 16px;
}

.next-reminder {
  margin-top: 8px;
  font-size: 13px;
  color: #67c23a;
  background: #f0f9eb;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

.last-reminder {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.reminder-time {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

.personal-center {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background: linear-gradient(135deg, #1e5799 0%,#207cca 100%);
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
}

.logo .iconfont {
  font-size: 28px;
  margin-right: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.welcome {
  margin-right: 15px;
  font-size: 14px;
}

.main-container {
  display: flex;
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
}

.sidebar {
  width: 260px;
  margin-right: 20px;
}

.user-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.user-details h3 {
  margin: 15px 0 5px;
  font-size: 18px;
}

.user-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.side-menu {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.side-menu .iconfont {
  margin-right: 10px;
  font-size: 18px;
}

.side-menu .el-menu-item {
  cursor: pointer;
}

.side-menu .el-menu-item.active {
  background-color: #ecf5ff;
  color: #409EFF;
}

.content {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  color: #303133;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.notification-card {
  max-width: 700px;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-info {
  flex: 1;
}

.notification-info h3 {
  margin: 0 0 5px;
  font-size: 16px;
  color: #303133;
}

.notification-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.notification-settings {
  display: flex;
  align-items: center;
  gap: 15px;
}

.save-settings {
  margin-top: 30px;
  text-align: center;
}

.reminder-content {
  text-align: center;
  padding: 20px;
}

.reminder-icon {
  margin-bottom: 20px;
}

.reminder-message {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 10px;
}
</style>